package com.billionsfinance.hessian.db.core.pool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;

/**
 * 数据库连接池管理类
 */
public class DBPoolMgr {

	private static final Logger LOGGER = LoggerFactory.getLogger(DBPoolMgr.class);

	public static String STRATEGY_POOL_NAME = "mysql";

	private static IDBPool strategyPool;

	public static boolean initPool(String dbDriver, String url, String username, String password) {
		if (strategyPool == null) {
			strategyPool = createPools(STRATEGY_POOL_NAME, dbDriver, url, username, password);
		}
		return strategyPool != null;
	}

	/**
	 * 根据指定属性创建连接池实例.
	 */
	private static IDBPool createPools(String poolName, String driver, String url, String user, String password) {
		try {
			IDBPool pool = new BoneCPDBPool(driver, url, user, password);
			String msg = String.format("加载配置连接池:%s,URL:%s完成！", poolName, url);
			LOGGER.info(msg);
			return pool;
		} catch (Exception e) {
			LOGGER.error("创建db连接池失败 poolName : " + poolName, e);
			return null;
		}
	}

	public static void closePools() {
		if (strategyPool != null) {
			strategyPool.shutdown();
			strategyPool = null;
		}
		LOGGER.info("数据库连接池关闭成功");
	}

	public static void closeStrategyPools() {
		if (strategyPool != null) {
			strategyPool.shutdown();
			strategyPool = null;
		}
		LOGGER.info("Strategy数据库连接池关闭成功");
	}

	public static Connection getStrategyConn() {
		Connection conn = strategyPool.getConnection();
		return conn;
	}

	public static String getStrategyPoolState() {
		if (strategyPool != null) {
			return strategyPool.getState();
		}
		return null;
	}

}
